﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InterfazConsultas;
using System.Reflection;
using Dominio.Entidades;
using System.Data;
using System.IO;

namespace Dominio.Logica
{
    public class ManejadorConsultas
    {
        private static List<Assembly> ListaAssemblies = null;

        private static List<IConsulta> ListaConsultas;

        private static List<IConsulta> CargarAssemblies()
        {
            IConsulta ICons = null;
            ListaConsultas = new List<IConsulta>();
            ListaAssemblies = CargarDll();
            foreach (Assembly Assembly in ListaAssemblies)
            {
                foreach (Type i in Assembly.GetTypes())
                {
                    if (typeof(IConsulta).IsAssignableFrom(i))
                    {
                        ICons = (IConsulta)Activator.CreateInstance(i);
                        ListaConsultas.Add(ICons);
                    }
                }
            }
            return ListaConsultas;
        }

        private static List<Assembly> CargarDll()
        {
            //Carga las Dll que están cargadas en la BD
            AgenciaEntities contexto = Contexto.GetContexto();
            List<string> ListaAssemblies_aux = contexto.Consultas.Select(o => o.RutaAssembly).ToList();
            List<Assembly> ListaAssemblies = new List<Assembly>();
            Assembly Assembly;
            foreach (var dir in ListaAssemblies_aux)
            {
                try
                {
                    Assembly = Assembly.LoadFile(dir);
                    ListaAssemblies.Add(Assembly);
                }
                catch (FileNotFoundException)
                {
                    
                }
                
            }
            return ListaAssemblies;
        }

        public static List<IConsulta> ObtenerListaConsultas() 
        {
            return CargarAssemblies();
        }


        public static DataSet EjecutarConsulta(string ConsultaAEjecutar)
        {
            Consultas consulta = new Consultas();
            DataSet Datos = consulta.EjecutarConsulta(ConsultaAEjecutar);
            return Datos;
        }
    }
}
